package com.ezlcp.form.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.base.entity.JsonPageResult;
import com.ezlcp.commons.base.entity.JsonResult;
import com.ezlcp.commons.dto.Datasource;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.DruidUtils;
import com.ezlcp.form.service.DatasourceServiceImpl;
import com.ezlcp.form.service.EntityServiceImpl;
import com.ezlcp.form.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;

@Slf4j
@RestController
@RequestMapping("/ezlcp/form/datasource")
@Tag(name = "自定义的数据库连接")
public class DatasourceController extends BaseController<Datasource> {
    @Resource
    DatasourceServiceImpl datasourceService;
    @Resource
    EntityServiceImpl entityService;

    @Operation(summary = "检查数据源标识符是否重复")
    @PostMapping("checkDsRepeat")
    public JsonResult checkDsRepeat(@Parameter(description = "标识符") @RequestParam("identifier") String identifier,
                                    @Parameter(description = "主键Id") @RequestParam(value = "dsId", required = false) String dsId) {
        boolean repeat = datasourceService.checkKeyRepeat(identifier, dsId);
        if (repeat) {
            //标识符不能重复，请重新输入
            return JsonResult.Fail("datasource.repeat");
        }
        return JsonResult.Success("common.handleSuccess");
    }

    @Operation(summary = "选择自定义数据源")
    @PostMapping("/selectDataSource")
    public  JsonResult selectDataSource(@Parameter(description = "模块ID") @RequestParam("moduleId") String moduleId){
        JsonResult result = JsonResult.getSuccessResult("common.handleSuccess");
        var data = datasourceService.selectDataSource(moduleId);
        result.setData(data);
        return result;
    }

    @Operation(summary = "测试数据库是否能连上")
    @PostMapping("testConnection")
    public JsonResult testConnection(@Parameter(description = "主键Id") @RequestParam(value = "dsId") String dsId) {
        if (StringUtils.isEmpty(dsId)) {
            return JsonResult.Fail("common.paramError");
        }
        var entity = datasourceService.getById(dsId);
        if (entity == null) {
            return JsonResult.Fail("common.paramError");
        }
        String detail = entity.getDetail();
        String dbType = DruidUtils.testConnection(detail);
        //无法建立连接
        if (StringUtils.isEmpty(dbType)) {
            //数据库连接失败
            return JsonResult.Fail("datasource.connFail");
        }
        //连接成功
        return JsonResult.Success("datasource.connSuccess");
    }

    @Operation(summary = "根据主键ID删除记录", description = "删除一条记录")
    @PostMapping("del")
    @Override
    public JsonResult del(@RequestParam(value = "id") String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.Fail("common.paramError");
        }
        if(entityService.isDataSourceUsed(id)){
            // 数据源已经被使用，请先删除关联的实体！
            return JsonResult.Fail("datasource.cantDelete");
        }
        datasourceService.delDataSource(id);
        JsonResult result = JsonResult.Success("common.delSuccess");
        logService.saveSystemLog(getComment(), "delete", id, "");
        datasourceService.pushAll2Nacos();
        return result;
    }

    @Override
    public JsonResult save(@Validated @RequestBody Datasource entity, BindingResult validResult) throws Exception {
        boolean repeat = datasourceService.checkKeyRepeat(entity.getIdentifier(), entity.getDsId());
        if (repeat) {
            //标识符不能重复，请重新输入
            return JsonResult.Fail("datasource.repeat");
        }
        String detail = entity.getDetail();
        String dbType = DruidUtils.testConnection(detail);
        //无法建立连接
        if (StringUtils.isEmpty(dbType)) {
            //数据库连接失败
            return JsonResult.Fail("datasource.connFail");
        }
        entity.setDbType(dbType);
        DataSource ds = null;
        try {
            JSONArray array = JSONArray.parseArray(detail);
            for (int i = 0; i < array.size(); i++) {
                var object = array.getJSONObject(i);
                String key = object.getString("prop");
                //密码改为密文保存
                if ("password".equals(key)) {
                    String value = object.getString("value");
                    object.put("value", DruidUtils.getEncryptPassword(value));
                    break;
                }
            }
            entity.setDetail(JSON.toJSONString(array));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return JsonResult.Fail("common.paramError");
        }
        var result = super.save(entity, validResult);
        if (result.isSuccess()) {
            datasourceService.pushAll2Nacos();
        }
        return result;
    }

    @Override
    public JsonPageResult getAll() {
        return JsonPageResult.getFail("common.apiClose");
    }

    @Override
    public BaseService getBaseService() {
        return datasourceService;
    }

    @Override
    public String getComment() {
        return "自定义的数据库连接";
    }
}